package com.wenx.v3system.modular.platform.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wenx.v3secure.enums.PlatformPermission;
import com.wenx.v3system.modular.platform.domain.dto.PlatformRoleDto;
import com.wenx.v3system.modular.platform.domain.query.PlatformRoleQuery;
import com.wenx.v3system.modular.platform.service.PlatformPermissionService;
import com.wenx.v3system.modular.platform.service.PlatformRoleMenuService;
import com.wenx.v3system.modular.platform.service.PlatformRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 平台权限服务实现类
 *
 * @author wenx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PlatformPermissionServiceImpl implements PlatformPermissionService {

    private final PlatformRoleService platformRoleService;
    private final PlatformRoleMenuService platformRoleMenuService;


    @Override
    public List<String> getAllPermissionCodes() {
        return Arrays.asList(
                PlatformPermission.PLATFORM_ALL_CODE,
                PlatformPermission.TENANT_READ_CODE,
                PlatformPermission.TENANT_ALL_CODE,
                PlatformPermission.PLATFORM_USER_READ_CODE,
                PlatformPermission.PLATFORM_USER_ALL_CODE,
                PlatformPermission.PLATFORM_ROLE_READ_CODE,
                PlatformPermission.PLATFORM_ROLE_ALL_CODE,
                PlatformPermission.SYSTEM_CONFIG_CODE,
                PlatformPermission.SYSTEM_ALL_CODE
        );
    }

    @Override
    public IPage<?> getRolesWithMenusPage(PlatformRoleQuery query) {
        // 获取角色分页数据
        IPage<?> rolesPage = platformRoleService.page(query);
        
        // 为每个角色添加菜单权限信息
        if (rolesPage.getRecords() != null && !rolesPage.getRecords().isEmpty()) {
            rolesPage.getRecords().stream()
                .filter(PlatformRoleDto.class::isInstance)
                .map(PlatformRoleDto.class::cast)
                .forEach(roleDto -> {
                    List<String> menuCodes = platformRoleMenuService.getMenuCodesByRoleId(roleDto.getId());
                    roleDto.setMenuCodes(menuCodes);
                    // 前端页面期望permissions字段，设置为与menuCodes相同的值
                    roleDto.setPermissions(menuCodes);
                });
        }
        
        return rolesPage;
    }

}